<?php
class ItsStocksInController extends AppController {
    var $name = 'ItsStocksIn';

    var $viewPath = 'its/stocks_in';

    var $pageTitle = 'Stock in Information';

    var $uses = array('ItsStockInHead','ItsStockIn', 'Supplier', 'Warehouse', 'Product', 'ProductSerial', 'RunningNo');

    var $paginate = array(
        'ItsStockInHead' => array(
                'order' => 'ItsStockInHead.id DESC'
            )
    );

    const ITS_STOCK_IN_TYPE = 'STI';

    function beforeFilter() {
        parent::beforeFilter();
        $this->set('parentNav', 'its_stocks_in');
    }

    function display() {
        parent::display('ItsStockInHead');
        $this->paginate['ItsStockInHead']['contain'] = array('User', 'Supplier');

        $op = array(
            'stock_in_no' => 'LIKE',
            'warehouse_id' => '=',
            'supplier_id' => '=',
            'po_no' => '=',
            'cust_pr_no' => '=',
        );

        $this->_checkBetweenSearch('ItsStockInHead', 'stock_in_date');
        $this->_paging('ItsStockInHead', $op);
    }

    function save() {
        $its_stock_in_head_id = null;
        $is_success = true;
        $collector_id = $this->Auth->user('id');

        if (!empty($this->data)) {

            // เรียงลำดับรายการใหม่ กรณีลบแถว Index เปลี่ยน เรียงตามลำดับที่ป้อนเข้ามา (key)
            $this->adjustRowIndex($this->data['ItsStockIn']);
            
            // ตรวจสอบว่ามีสินค้าอยู่ในใบ ItsStockInHead
            if(count($this->data['ItsStockIn']) == 0) {
                $this->Session->setFlash("Stock in must have at least one product !!!.", 'flash/fail');
            } else {
                $this->ItsStockInHead->query("BEGIN");

                // Generate Stock in no
                $year = $this->Utility->getThaiYear();
                $runno = $this->RunningNo->getNextStockNo(self::ITS_STOCK_IN_TYPE, $year);
                $this->data['ItsStockInHead']['stock_in_no'] = self::ITS_STOCK_IN_TYPE . $year . $runno;
                $this->data['ItsStockInHead']['collector_id'] = $collector_id;

                // Save ItsStockInHead && ItsStockIn
                if($this->ItsStockInHead->saveAll($this->data, array('validate' => 'first', 'atomic' => false))) {
                    $its_stock_in_head_id = $this->ItsStockInHead->id;

                    // Update Product current stock
                    foreach($this->data['ItsStockIn'] as $ItsStockIn) {
                        $product_id = $ItsStockIn['product_id'];
                        $this->Product->id = $product_id;
                        $current_stock = $this->Product->field('current_stock') + $ItsStockIn['stock_in_qty'];
                        $is_success &= $this->Product->saveField('current_stock', $current_stock);
                        $is_success &= $this->Product->saveField('last_stock_in_date', date('Y-m-d'));
                        $is_success &= $this->Product->saveField('cost', $ItsStockIn['cost']);

                        //ดึงรายการ ITS Stock in
                        $this->ItsStockIn->contain();
                        $stockIn = $this->ItsStockIn->find('first', array('conditions' => array(
                                    'its_stock_in_head_id' => $its_stock_in_head_id,
                                    'product_id' => $product_id
                                )
                            )
                        );

                        // หา Stock out Priority ล่าสุดสำหรับ Product นี้
                        $this->ProductSerial->contain();
                        $productSerial = $this->ProductSerial->find('first', array(
                                'conditions' => array(
                                    'product_id' => $product_id
                                ),
                                'fields' => array('stock_out_priority'),
                                'order' => array('stock_out_priority DESC'),
                                'limit' => 1
                            )
                        );
                        // ถ้าเคย stock in แล้ว SoP เริ่มต้นคือลำดับถัดไป ถ้ายังเริ่มที่ 1
                        $stock_out_priority = !empty($productSerial)? $productSerial['ProductSerial']['stock_out_priority'] + 1: 1;

                        // วนลูป Product Serial
                        $product_serial_count = $ItsStockIn['stock_in_qty'];
                        for ($j = 0; $j < $product_serial_count; ++$j) {
                            // คัดลอก field
                            $product_serial['ProductSerial'] = array();
                            $product_serial['ProductSerial']['id'] = null;
                            $product_serial['ProductSerial']['stock_out_priority'] = $stock_out_priority++;
                            $product_serial['ProductSerial']['cost'] = $ItsStockIn['cost'];
                            $product_serial['ProductSerial']['product_id'] = $product_id;
                            $product_serial['ProductSerial']['location_id'] = $ItsStockIn['location_id'];
                            $product_serial['ProductSerial']['its_stock_in_id'] = $stockIn['ItsStockIn']['id'];
                            $product_serial['ProductSerial']['its_stock_in_type'] = ItsStockIn::STOCK_IN_TYPE;
                            $product_serial['ProductSerial']['serial_no'] = null;
                            $product_serial['ProductSerial']['other_information'] = null;
                            $product_serial['ProductSerial']['is_active_flag'] = true;
                            $this->ProductSerial->create();
                            $is_success &= $this->ProductSerial->save($product_serial);
                        }
                        if(!$is_success) {
                            break;
                        }
                    }
                } else {
                    $is_success = false;
                }
                if ($is_success) {
                    $this->ItsStockInHead->query("COMMIT");;
                    $its_stock_in_head_id = $this->ItsStockInHead->id;
                    $this->Session->setFlash('Stock in save succesfull.', 'flash/ok');
                } else {
                    $this->ItsStockInHead->query("ROLLBACK");
                    $this->Session->setFlash('Stock in save fail!!!.', 'flash/fail');
                }
            }
        }
        $this->data['ItsStockInHead']['warehouse_id'] = null;
        $this->data['ItsStockIn'] = null;
        $this->setAction('view', $its_stock_in_head_id);
    }

    function view($id = null) {
        // edit
        if ($id != null) {
            $this->ItsStockInHead->contain(array('Supplier', 'Warehouse', 'ItsStockIn' => array('Product' => array('Unit'))));
            $this->data = $this->ItsStockInHead->findById($id);

            $this->_neighbors($id, $this->ItsStockInHead, array('fields' => array('id')));
            $this->set('mode', 'edit');
        } else {
            $this->set('warehouses', $this->Warehouse->find('list', array('order' => 'name')));
            $this->set('suppliers', $this->Supplier->find('list', array('order' => 'name')));
            $this->set('stock_in_by', $this->Auth->user('name')); // กำหนดผู้ทำการ stock in
            $this->set('today', date("d/m/Y"));                 // กำหนด default วันที่ stock in
            $this->set('mode', 'add');

        }

        $this->render('view');
    }

    function print_view($id) {
        $this->layout = 'print';
        $this->data = $this->ItsStockInHead->findForPrintById($id);
    }

    function popup_search() {
        parent::popup_search();

        $this->set('warehouses', $this->Warehouse->find('list', array('fields' => array('id', 'name'))));
        $this->set('suppliers', $this->Supplier->find('list', array('fields' => array('id', 'name'), 'order' => 'Supplier.name')));
        $this->set('popupWidth', 500);
    }

}
?>
